import React,{Component} from "react";
import Header from './components/Header'
import List from './components/List'
import Footer from './components/Footer'
import './App.css'
export default class App extends Component{
    state={
        todoList:localStorage.getItem('todoList')? JSON.parse(localStorage.getItem('todoList')):[]
    }
  //  处理复选框
    handleIschecked(id){
        this.setState(
            {
                todoList:this.state.todoList.map(item=>{
                    if(item.id===id)item.isChecked = !item.isChecked
                    return item
                })
            }
        )
    }
  //  回车添加
    handleAdd(e){
      if(e.keyCode===13){
          const value = e.target.value.trim()
          if(!value){
              window.alert('请输入标题！')
          }else if(this.state.todoList.find(v=>v.name===value)){
              window.alert('输入内容重复！')
          }else{
              this.setState(
                  {
                      todoList:[
                          {
                              id:Math.random().toString(36).slice(2),
                              name:value,
                              isChecked:false
                          },
                          ...this.state.todoList
                  ]})
              e.target.value = ''
          }
      }
    }
    //删除某一项
    deleteTodo(id){
        this.setState({
            todoList:this.state.todoList.filter(v=>v.id!==id)
        })
    }

  //  批量添加/删除
    changeAllIsChecked(isChecked){
        this.setState({
            todoList:this.state.todoList.map(v=>{v.isChecked=isChecked;return v})
        })
    }
  //  删除已选项
    deleteSelected(){
        this.setState({
            todoList:this.state.todoList.filter(v=>!v.isChecked)
        })
    }
  render(){
    return (
        <div className="todo-container">
            <div className="todo-wrap">
                <Header handleAdd={this.handleAdd.bind(this)}/>
                <List deleteTodo={this.deleteTodo.bind(this)} handleIschecked={this.handleIschecked.bind(this)} todoList={this.state.todoList}/>
                <Footer todoList={this.state.todoList} changeAllIsChecked={this.changeAllIsChecked.bind(this)} deleteSelected={this.deleteSelected.bind(this)}/>
            </div>
        </div>
    )
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
        localStorage.setItem('todoList',JSON.stringify(this.state.todoList))
  }
}
